module top_module(
    input clk,
    input in,
    input reset,    // Synchronous reset
    output [7:0] out_byte,
    output done
);

    /*
    parameter IDLE = 0, DATA = 1, CHECK = 2, STOP = 3, ERROR = 4;
    
    reg[2:0] state, next_state;
    reg[3:0] cnt;
    reg[7:0] out;
    reg check;
    wire odd, start;
    
    parity parity_inst(
        .clk(clk),
        .reset(reset | start),
        .in(in),
        .odd(odd));    
    
    //transition
    always@(*)begin
        start = 0;
        case(state)
            IDLE:begin next_state=in?IDLE:DATA; start=1; end
            DATA:next_state=(cnt==8)?CHECK:DATA;
            CHECK:next_state=in?STOP:ERROR;
            STOP:begin next_state=in?IDLE:DATA; start=1; end
            ERROR:next_state=in?IDLE:ERROR;
        endcase
    end
    
    //state
    always@(posedge clk)begin
        if(reset)
            state<=IDLE;
        else
            state<=next_state;
    end
    
    //cnt
    always@(posedge clk)begin
        if(reset)
            cnt<=0;
        else
            case(state)
                DATA:cnt<=cnt+1;
                default:cnt<=0;
            endcase
    end
    
    //out
    always@(posedge clk)begin
        if(reset)
            out<=0;
        else
            case(next_state)
                DATA:out<={in,out[7:1]};
            endcase
    end
    
    //check
    always@(posedge clk)begin
        if(reset)
            check<=0;
        else
            check<=odd;
    end
    
    assign out_byte=out;
    assign done=check&(state==STOP);
    */

    // Modify FSM and datapath from Fsm_serialdata
    parameter START = 0, CHECK = 9, STOP = 10, IDEL = 11, ERROR = 12;
    reg [4:0] state, next_state;
    reg valid, start;

    always @(*) begin
        start = 0;
        case (state)
            IDEL: begin next_state = in ? IDEL : START; start = 1; end
            STOP: begin next_state = in ? IDEL : START; start = 1; end
            CHECK: next_state = in ? STOP : ERROR;
            ERROR: next_state = in ? IDEL : ERROR;
            default: next_state = state + 1;
        endcase  
    end
    
    always @(posedge clk)
        if (reset)
            state <= IDEL;
        else begin
            state <= next_state;
            valid <= odd;
        end
    
    always @(posedge clk)
        if ((0 <= state) & (state < 8))
            out_byte[state] <= in;
    
    wire odd;
    parity check(clk, reset | start, in, odd);
    
    assign done = (valid & (state == STOP));
    // New: Add parity checking.

endmodule
